package com.sxfq.loansupermarket.backsystem.modular.basicData.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.constant.tips.Tip;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.Deptinfos;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.*;
import com.sxfq.loansupermarket.backsystem.modular.basicData.service.PointRewordService;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.DaulInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 *
 * @author py
 * @Date 2018年4月19日23:15:54
 */
@Controller
@RequestMapping("/pointReword")
public class PointRewordController extends BaseController {
    @Autowired
    PointRewordService pointRewordService;

    @Autowired
    private SqlMapper sqlMapper;

    private String PREFIX = "/basicData/pointReword/";

    /**
     * 跳转到积分商城管理
     */
    @RequestMapping("")
    public String pointReword(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getUser().getArealist() == null) {
            String sql1 = "select area_abbreviation as areaAbbreviation,area as area from dept a where length(a.pids)>4 " +
                    " and version='" + ShiroKit.getUser().getCompanyVersion() + "' group by a.area order by a.num desc";
            List<Deptinfos> arealist = sqlMapper.selectList(sql1, Deptinfos.class);
            ShiroKit.getUser().setArealist(arealist);
        }
        model.addAttribute("arealist", ShiroKit.getUser().getArealist());
        return PREFIX + "pointReword.html";
    }

    /**
     * 跳转到积分商城 添加
     */
    @RequestMapping(value = "/pointReword_add/{id}")
    public String pointRewordAdd(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getUser().getArealist() == null) {
            String sql1 = "select area_abbreviation as areaAbbreviation,area as area from dept a where length(a.pids)>4 " +
                    " and version='" + ShiroKit.getUser().getCompanyVersion() + "' group by a.area order by a.num desc";
            List<Deptinfos> arealist = sqlMapper.selectList(sql1, Deptinfos.class);
            ShiroKit.getUser().setArealist(arealist);
        }
        model.addAttribute("arealist", ShiroKit.getUser().getArealist());
        String randomNumbersql = "select DATE_FORMAT(now(),'%Y%m%d%k%i%S') as randomNumber from dual";
        DaulInfo infos = sqlMapper.selectOne(randomNumbersql, DaulInfo.class);
        model.addAttribute("num", infos.getRandomNumber());
        return PREFIX + "pointReword_add.html";
    }
    /**
     * 跳转到预约客户管理详情页面
     */
    @RequestMapping(value = "/pointReword_update/{id}")
    public String pointRewordUpdate(@PathVariable String id, Model model) {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        PointRewordIconinfo info;
        String sqlStr ="select * from point_reword_iconinfo where product_id='"+id+"' and mainFigure=1 ";
         info = sqlMapper.selectOne(sqlStr,PointRewordIconinfo.class);
        if(info==null){
            String curStr ="select * from point_reword_iconinfo where product_id='"+id+"' limit 1 ";
            PointRewordIconinfo iconinfo = sqlMapper.selectOne(curStr,PointRewordIconinfo.class);
            if(iconinfo!=null){
                info=iconinfo;
            }else{
                return "1";
            }
        }
        PointRewordInfo pointRewordInfo = pointRewordService.selectOneById(id);
        model.addAttribute("pointRewordInfo", pointRewordInfo);
        model.addAttribute("info", info);
        model.addAttribute("num", id);
        return PREFIX + "pointReword_edit.html";
    }

    @RequestMapping(value = "/pointReword_getAdd/{id}")
    @ResponseBody
    public int pointReword_getAdd(@PathVariable String id) {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        PointRewordIconinfo info;
        String sqlStr ="select * from point_reword_iconinfo where product_id='"+id+"' and mainFigure=1 ";
        info = sqlMapper.selectOne(sqlStr,PointRewordIconinfo.class);
        if(info==null){
            String curStr ="select * from point_reword_iconinfo where product_id='"+id+"' limit 1 ";
            PointRewordIconinfo iconinfo = sqlMapper.selectOne(curStr,PointRewordIconinfo.class);
            if(iconinfo!=null){
                return 1;
            }else{
                return 2;
            }
        }else{
            return 1;
        }
    }


    @RequestMapping(value = "/pointReword_getUpdate/{id}")
    @ResponseBody
    public int pointReword_getUpdate(@PathVariable String id) {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        PointRewordIconinfo info;
        String sqlStr ="select * from point_reword_iconinfo where product_id='"+id+"' and mainFigure=1 ";
        info = sqlMapper.selectOne(sqlStr,PointRewordIconinfo.class);
        if(info==null){
            String curStr ="select * from point_reword_iconinfo where product_id='"+id+"' limit 1 ";
            PointRewordIconinfo iconinfo = sqlMapper.selectOne(curStr,PointRewordIconinfo.class);
            if(iconinfo!=null){
                return 1;
            }else{
                return 2;
            }
        }else{
            return 1;
        }
    }

    /**
     * 跳转到积分商品管理详情页面
     */
    @RequestMapping(value = "/pointReword_details/{id}")
    public String pointRewordDetails(@PathVariable String id, Model model) {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sqlStr ="select a.*,b.product_description from point_reword_iconinfo a left join point_reword_info b on a.product_id = b.id " +
                "where product_id='"+id+"' and mainFigure!=1 ";
        List<PointRewordIconinfo> listInfo = sqlMapper.selectList(sqlStr,PointRewordIconinfo.class);
        PointRewordInfo pointRewordInfo = pointRewordService.selectOneById(id);
        model.addAttribute("pointRewordInfo", pointRewordInfo);
        model.addAttribute("info", listInfo);
        model.addAttribute("num", id);
        return PREFIX + "pointReword_details.html";
    }

    /**
     * 商品管理列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object testrInfoList(SearchPointRewordInfo info, HttpServletRequest request) {
        Page<PointRewordInfo> page = new PageFactory<PointRewordInfo>().defaultPage();
        try {
            info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
            info.setLimitIndex(page.getSize());
            page.setCurrent(0);
            List<PointRewordInfo> list = pointRewordService.selectPageListByQueryGetMap(page, info);
            if (list.size() == 0) {
                info.setStartIndex(0);
                list = pointRewordService.selectPageListByQueryGetMap(page, info);
            }
            page.setTotal(pointRewordService.getQueryPagesPointCount(page, info));
            page.setRecords(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    /**
     * 保存新增商品
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public int add(PointRewordInfo info,BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        return pointRewordService.insert(info);
    }

    /**
     * 删除预约客户
     */
    @RequestMapping(value = "/delete/{id}")
    @ResponseBody
    public Tip delete(@PathVariable String id) throws Exception {
        pointRewordService.delete(id);
        return SUCCESS_TIP;
    }

    /**
     * 修改商品信息
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public int update(PointRewordInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        return pointRewordService.update(info);
    }

    /**
     * 修改商品信息
     */
    @RequestMapping(value = "/updatePoint")
    @ResponseBody
    public int updatePoint(PointRewordInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        return pointRewordService.updatePoint(info);
    }

    @RequestMapping(value = "/getList", method = RequestMethod.POST)
    @ResponseBody
    public  List<Map<String,Object>> getList() {
        List<Map<String,Object>> list= pointRewordService.list();
        return list;
    }

    /**
     * 上传图片(上传到项目的webapp/static/img)
     */
    //@Transactional
    @RequestMapping(method = RequestMethod.POST, path = "/upLoadProdcut/{cri}")
    @ResponseBody
    public String upLoadProcess(@RequestPart("file") MultipartFile picture,
                                @PathVariable String cri) {
        return pointRewordService.uploadPoint(picture,cri);
    }


    /**
     * 上传图片(上传到项目的webapp/static/img)
     */
    //@Transactional
    @RequestMapping(method = RequestMethod.POST, path = "/upLoadProdcutTwo/{cri}")
    @ResponseBody
    public String upLoadProdcutTwo(@RequestPart("file") MultipartFile picture,
                                @PathVariable String cri) {
        return pointRewordService.upLoadProdcutTwo(picture,cri);
    }


    //获取 图片
    @RequestMapping(value = "/getImgcancel", method = RequestMethod.POST)
    @ResponseBody
    public List<PointRewordIconinfo> getImgcancel(String num) throws Exception {
        String sql = "select * from point_reword_iconinfo where product_id='" + num + "' and mainFigure=1";
        List<PointRewordIconinfo> info2 = sqlMapper.selectList(sql, PointRewordIconinfo.class);
        return info2;
    }

    //获取 图片
    @RequestMapping(value = "/getImgcancelTwo", method = RequestMethod.POST)
    @ResponseBody
    public List<PointRewordIconinfo> getImgcancelTwo(String num) throws Exception {
        String sql = "select * from point_reword_iconinfo where product_id='" + num + "' ";
        List<PointRewordIconinfo> info2 = sqlMapper.selectList(sql, PointRewordIconinfo.class);
        return info2;
    }

    //删除图片
    @RequestMapping(value = "/delteCancel", method = RequestMethod.POST)
    @ResponseBody
    public int delteProcess(String id) throws Exception {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "delete from point_reword_iconinfo where id='" + id + "'";
        return sqlMapper.delete(sql);
    }

    /**
     * 修改上传图片(上传到项目的webapp/static/img)
     */
    //@Transactional
    @RequestMapping(method = RequestMethod.POST, path = "/updateProdcut/{cir}")
    @ResponseBody
    public String updateProduct(@RequestPart("file") MultipartFile picture,
                                @PathVariable String cir) {
        return pointRewordService.updatePoint(picture,cir);
    }
}